<template>
  <el-container>
    <el-header
        class="user-center-header"
        :style="{
        backgroundImage: 'url(https://img.neptech.net/i/2025/06/17/i854ah.webp)'
      }"
    >
      <h1 class="header-title">个人中心</h1>
    </el-header>
    <el-container>
      <el-main>
        <el-card class="user-center-card">
          <div v-if="loading" class="loading-container">
            <el-empty description="加载中..." />
          </div>
          <div v-else-if="error" class="error-container">
            <el-empty description="加载失败" :image="errorImage" />
          </div>
          <div v-else>
            <div class="avatar-section">
              <el-tooltip content="点击更换头像" placement="top">
                <div @click="triggerFileInput">
                  <el-avatar
                      :size="120"
                      :src="avatarPreview || userInf.data.avatarUrl || ''"
                      class="user-avatar"
                  >
                    <el-icon><User /></el-icon>
                  </el-avatar>
                  <input
                      ref="fileInput"
                      type="file"
                      @change="handleFileChange"
                      accept="image/*"
                      style="display: none"
                  />
                </div>
              </el-tooltip>
              <el-text class="user-name" size="large" tag="h3">
                {{ userInf.data.userName }}
              </el-text>

              <div v-if="selectedFile" class="upload-controls">
                <el-button
                    type="primary"
                    @click="uploadAvatar"
                    :loading="uploading"
                >
                  确认上传
                </el-button>
                <el-button @click="cancelUpload">取消</el-button>
                <el-text type="danger" v-if="uploadError">
                  {{ uploadError }}
                </el-text>
              </div>
            </div>

            <el-row :gutter="20" class="info-section">
              <el-col :span="24">
                <el-descriptions
                    :column="1"
                    border
                    :title="isEdit ? '编辑个人信息' : '个人信息'"
                >
                  <el-descriptions-item label="角色">
                    {{ roleMap[userInf.data.roleId] }}
                  </el-descriptions-item>
                  <el-descriptions-item label="昵称">
                    <el-input
                        v-if="isEdit"
                        v-model="editedInfo.nickname"
                        placeholder="请输入昵称"
                    />
                    <span v-else>{{ editedInfo.nickname }}</span>
                  </el-descriptions-item>
                  <el-descriptions-item label="联系方式">
                    <el-input
                        v-if="isEdit"
                        v-model="editedInfo.contact"
                        placeholder="请输入联系方式"
                    />
                    <span v-else>{{ editedInfo.contact }}</span>
                  </el-descriptions-item>
                  <el-descriptions-item
                      v-if="isEdit"
                      label="修改密码"
                  >
                    <el-input
                        v-model="editedInfo.password"
                        type="password"
                        placeholder="新密码"
                        show-password
                    />
                  </el-descriptions-item>
                  <el-descriptions-item
                      v-if="isEdit"
                      label="确认密码"
                  >
                    <el-input
                        v-model="editedInfo.confirmPassword"
                        type="password"
                        placeholder="确认新密码"
                        show-password
                    />
                    <el-text type="danger" v-if="passwordError">
                      {{ passwordError }}
                    </el-text>
                  </el-descriptions-item>
                </el-descriptions>
              </el-col>
            </el-row>

            <div class="action-buttons">
              <template v-if="isEdit">
                <el-button
                    type="primary"
                    @click="saveChanges"
                    :loading="saving"
                >
                  确认修改
                </el-button>
                <el-button @click="resetChanges">取消</el-button>
              </template>
              <template v-else>
                <el-button
                    type="primary"
                    @click="isEdit = true"
                    :loading="saving"
                >
                  编辑个人信息
                </el-button>
                <el-button type="info" @click="router.back()">
                  返回
                </el-button>
              </template>
            </div>
          </div>
        </el-card>
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup lang="ts">
import { User } from '@element-plus/icons-vue'
import AllUserApi from "@/api/Backend/AllUserApi";
import router from "@/router";
import { useRoute } from 'vue-router'
import { userInfo } from '@/stores/userinfo';
const userStore = userInfo()
const route = useRoute()

// 用户信息
const userInf = ref({
  data: {
    userId: 0,
    userName: "",
    nickname: "",
    contact: "",
    avatarUrl: "",
    roleId: 0,
  },
})

// 编辑状态
const editedInfo = ref({
  nickname: "",
  contact: "",
  password: "",
  confirmPassword: "",
})

// 角色映射
const roleMap: Record<number, string> = {
  1: "管理员",
  2: "教师",
  3: "学生",
}

// 加载状态
const loading = ref(true)
const error = ref(null)
const saving = ref(false)
const isEdit = ref(false)

// 上传相关状态
const selectedFile = ref<File | null>(null)
const avatarPreview = ref<string | null>(null)
const uploading = ref(false)
const uploadError = ref<string | null>(null)
const fileInput = ref<HTMLInputElement | null>(null)

// 密码验证
const passwordError = computed(() => {
  if (
      editedInfo.value.password &&
      editedInfo.value.password !== editedInfo.value.confirmPassword
  ) {
    return "两次输入的密码不一致"
  }
  return ""
})

// 获取用户信息
const fetchUserInfo = async (userId: number) => {
  try {
    const response = await AllUserApi.getUserInfo(userId)
    if (response.code === 200) {
      userInf.value.data = response.data
      editedInfo.value = {
        nickname: response.data.nickname,
        contact: response.data.contact,
        password: "",
        confirmPassword: "",
      }
    } else {
      error.value = response.msg || "未知错误"
      ElMessage.error(error.value)
    }
  } catch (err) {
    error.value = "请求出错，请稍后重试"
    ElMessage.error(error.value)
    console.error("获取用户信息出错:", err)
  } finally {
    loading.value = false
  }
}

// 触发文件选择
const triggerFileInput = () => {
  fileInput.value?.click()
}

// 文件选择事件处理
const handleFileChange = (event: Event) => {
  const target = event.target as HTMLInputElement
  if (target.files && target.files.length > 0) {
    selectedFile.value = target.files[0]
    uploadError.value = null

    // 创建图片预览
    const reader = new FileReader()
    reader.onload = (e) => {
      avatarPreview.value = e.target?.result as string
    }
    reader.readAsDataURL(selectedFile.value)
  }
}

// 上传头像
const uploadAvatar = async () => {
  if (!selectedFile.value) {
    uploadError.value = "请先选择图片"
    return
  }

  uploading.value = true
  uploadError.value = null

  try {
    const response = await AllUserApi.uploadAvatar(
        userInf.value.data.userId,
        selectedFile.value
    )
    if (response.code === 200) {
      ElMessage.success("头像上传成功")
      userStore.userInfo.avatarUrl=response.data
      userInf.value.data.avatarUrl = response.data
      cancelUpload()
    } else {
      uploadError.value = response.msg || "上传失败"
      ElMessage.error(uploadError.value)
    }
  } catch (err) {
    uploadError.value = "上传出错，请稍后重试"
    ElMessage.error(uploadError.value)
    console.error("上传头像出错:", err)
  } finally {
    uploading.value = false
  }
}

// 取消上传
const cancelUpload = () => {
  selectedFile.value = null
  avatarPreview.value = null
  uploadError.value = null
}

// 保存修改
const saveChanges = async () => {
  if (passwordError.value) {
    ElMessage.warning("请确认两次输入的密码一致")
    return
  }

  saving.value = true

  try {
    // 先处理头像上传
    if (selectedFile.value) {
      await uploadAvatar()
    }

    // 准备更新数据
    const updateData = {
      userId: userInf.value.data.userId,
      nickname: editedInfo.value.nickname,
      contact: editedInfo.value.contact,
      ...(editedInfo.value.password && { password: editedInfo.value.password }),
    }

    const response = await AllUserApi.updateUser(updateData)

    if (response.code === 200) {
      ElMessage.success("用户信息更新成功")
      await fetchUserInfo(userInf.value.data.userId)
      isEdit.value = false
    } else {
      ElMessage.error(response.msg || "更新失败")
    }
  } catch (err) {
    ElMessage.error("保存出错，请稍后重试")
    console.error("保存出错:", err)
  } finally {
    saving.value = false
  }
}

// 重置修改
const resetChanges = () => {
  editedInfo.value = {
    nickname: userInf.value.data.nickname,
    contact: userInf.value.data.contact,
    password: "",
    confirmPassword: "",
  }
  cancelUpload()
  isEdit.value = false
}

onMounted(() => {
  // 从路由参数获取userId
  const userId = route.query.userId ? parseInt(route.query.userId as string) : null
  console.log(userId)
  if (userId) {
    fetchUserInfo(userId)
  } else {
    error.value = "未获取到用户ID"
    loading.value = false
  }
})
</script>

<style scoped>
.user-center-header {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 350px;
  padding: 0;
  background-position: center;
  background-size: cover;
}

.header-title {
  font-size: 40px;
  color: white;
}

.user-center-card {
  max-width: 800px;
  margin: 20px auto;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
  margin-bottom: 30px;
}

.user-avatar {
  cursor: pointer;
  transition: transform 0.3s;
}

.user-avatar:hover {
  transform: scale(1.05);
}

.user-name {
  margin: 0;
}

.upload-controls {
  display: flex;
  gap: 10px;
  align-items: center;
}

.info-section {
  margin-bottom: 30px;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
}

.loading-container,
.error-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}
</style>
